import java.util.Stack;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User: Administrator
 * Data: 2023 - 08 - 31
 * Time: 19:44
 */
//牛客 有效括号序列
public class Solution4 {
    //法一
    public boolean isValid (String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c1 = s.charAt(i);
            if(c1 == '(' || c1 == '{' || c1 == '[') {
                stack.push(c1);
            }else {
                if(stack.isEmpty()) {
                    return false;
                }else {
                    char c2 = stack.peek();
                    if(c1 == ')' && c2 == '(' || c1 == '}' && c2 == '{' || c1 == ']' && c2 == '[') {
                        stack.pop();
                    }else {
                        return false;
                    }
                }
            }
        }
        if(!stack.isEmpty()) {
            return false;
        }
        return true;
    }

    //法二 官方方法
    public boolean isValid1 (String s) {
        Stack<Character> st = new Stack<Character>();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '(')
                st.push(')');
            else if(s.charAt(i) == '[')
                st.push(']');
            else if(s.charAt(i) == '{')
                st.push('}');
            else if(st.isEmpty() || st.pop() != s.charAt(i))//右括号多于左括号，或括号不匹配
                return false;
        }
        return st.isEmpty();//左括号多于右括号
    }
}
